import React, { useEffect, useRef } from 'react'
import { getAveScore } from '../lib/publicMethod'
import { IVideoData } from '../interface/IVideoData'
import * as echarts from 'echarts';
import VCData from '../interface/VCData';

interface ICityToScore {
  city: string,
  aveScore: number
}
interface ICityToList {
  [key: string]: VCData[]
}
interface IProps {
  data: IVideoData[]
}
export default function CityBar(props: IProps) {
  const data: VCData[] = props.data
  const el = useRef<HTMLDivElement | null>(null)
  const ec = useRef<echarts.ECharts | null>(null)
  useEffect(() => {
    ec.current = echarts.init(el.current as HTMLDivElement)
  }, [])
  useEffect(() => {
    //按校区画图
    const cityToList: ICityToList = {}
    for (let i = 0; i < data.length; i++) {
      if (cityToList[data[i]['校区']]) {
        cityToList[data[i]['校区']].push(data[i])
      } else {
        cityToList[data[i]['校区']] = [data[i]]
      }
    }
    const cityToAveScore: ICityToScore[] = []
    Object.keys(cityToList).forEach(item => {
      cityToAveScore.push({
        city: item,
        aveScore: getAveScore(cityToList[item])
      })
    })
    cityToAveScore.sort((a, b) => a.aveScore - b.aveScore)
    const x: string[] = []
    const y: number[] = []
    for (let i = 0; i < cityToAveScore.length; i++) {
      x.push(cityToAveScore[i].city)
      y.push(cityToAveScore[i].aveScore)
    }
    (ec.current as echarts.ECharts).setOption({
      legend: {
        data: ['总分平均值']
      },
      xAxis: {
        data: x
      },
      yAxis: {},
      series: [{
        name: '总分平均值',
        type: 'bar',
        data: y,
        label: {
          show: true
        }
      }]
    })
  }, [data])
  return (
    <div className="show" ref={el}></div>
  )
}
